package main

import (
		"fmt"
		"encoding/json"
		"sync"
		"strings"
		"time"
	   )

type BinanceTicker struct {
	Symbol   string `json:"symbol"`
	BidPrice string `json:"bidPrice"`
	BidQty   string `json:"bidQty"`
	AskPrice string `json:"askPrice"`
	AskQty   string `json:"askQty"`
}
var (
		configFile_binance = "config/binance.json"
	)

func BinanceMarketsToRedis(inWg *sync.WaitGroup) error{
	defer inWg.Done()

	t := time.Now()
	
	// fmt.Printf("BinanceMarketsToRedis begin.\n")
	var wg sync.WaitGroup
	wg.Add(1)
	go BinanceMarketToRedis("", &wg)
	wg.Wait()

	fmt.Printf("BinanceMarketsToRedis duration: %s\n", time.Now().Sub(t))

	return nil
}

func formatAndInsert_binance(url string,source string,data []byte){
	var mdata []BinanceTicker
		err := json.Unmarshal(data, &mdata)
		if err != nil {
			fmt.Println("error:", err)
		}
	for v := range mdata {
		var skey = source + "_"+ strings.ToLower(mdata[v].Symbol)+"_last";
		//fmt.Printf("%s,%s\n",skey,mdata[v]);
		var sdata,err = json.Marshal(mdata[v])
			err = client.Set(skey, sdata, 0).Err()
			if err != nil {
				fmt.Printf("redis set failed!%s=%s,err=%s\n", skey,mdata[v],err)
			}
	}
}
func BinanceMarketToRedis(name string, wg *sync.WaitGroup){
	defer wg.Done()
	url := "https://api.binance.com/api/v3/ticker/bookTicker"
	body := httpGet(url)
	formatAndInsert_binance(url,"binance",body);
}
